
console.log("js");
		// 将变量和类定义放在全局作用域外
		class file{
			constructor(name, size,n)
			{
					this.name=name;
					this.size=size;
					this.n=n;
			}
		}
		class up_line{
			constructor(name,p,n)
			{
					this.name=name;
					this.p=p;
					this.n=n;
					this.is_pause=false;
			}
		}
	var files=new Array();
	var up_queue=new Array();
			// 异步执行函数包装器
		async function executeAsync(func, ...args) {
			return new Promise((resolve, reject) => {
				try {
					setTimeout(() => {
						try {
							const result = func(...args);
							resolve(result);
						} catch (error) {
							reject(error);
						}
					}, 0);
				} catch (error) {
					reject(error);
				}
			});
		}

	function Math_size(size){
				size=size+'B';
				if(parseFloat(size)>1024)
				{
					size=String((parseInt(size)/1024).toFixed(1))+'K';
				}
				if(parseFloat(size)>1024)
				{
					size=String((parseInt(size)/1024).toFixed(1))+'M';
				}
				if(parseFloat(size)>1024)
				{
					size=String((parseInt(size)/1024).toFixed(1))+'G';
				}
				if(parseFloat(size)>1024)
				{
					size=String((parseInt(size)/1024).toFixed(1))+'T';
				}
				return size;
			}
	//从服务器里读取用户文件库写入到数组中
	var xhr=new XMLHttpRequest();//创建一个 XMLHttpRequest请求的对象
	var url="";
	var get_files="get_files:"+localStorage.getItem("usr_name");
	xhr.open("POST",url,true);
	xhr.onreadystatechange=function()
	{
			if(xhr.status>=200&&xhr.status<300){
				if(xhr.responseText=="False"){
					window.alert("获取文件失败,请检查网络或刷新网站");
				}
				else{
					var text=xhr.responseText;
					var text_arr=text.split("\r\n\r\n");
					console.log(text_arr);
					for(var i=0;i<text_arr.length-1;i++){
						var arr=text_arr[i].split("\r\n");
						console.log(arr);
						files[i]=new file(String(arr[0]),Math_size(arr[1]),i);
					}
				}
			}else{
				 console.error('Error:', xhr.statusText);
			}
	}
 
	function file_delete(file_name){
				var is_success;
				var xhr=new XMLHttpRequest();//创建一个 XMLHttpRequest请求的对象
				var url="";
				var req="delete:"+localStorage.getItem("usr_name")+'/'+file_name;
				xhr.open("POST",url,true);
				xhr.onreadystatechange=function()
				{
				if(xhr.status>=200&&xhr.status<300){
						if(xhr.responseText=="False"){
							window.alert("删除文件失败,请检查网络或刷新网站");
							is_success="false";
						}
						else{
							is_success="success";
						}
					}else{
							is_success="false";
					}
				}
				xhr.send(JSON.stringify(req));//发送请求数据并将其转换为JSON格式
				return is_success;
			}

	var f_delete=function(n,file_table,file_list)
	{
		return async function() {
			 return new Promise((resolve, reject) =>{
				console.log("f_delete");
				if(file_delete(files[n].name)!="success"){
					files[n].n=-1;
					file_table.removeChild(file_list);
					console.log("success");
					resolve("success");
				}else{
					reject(new Error('Error:',"false"))
				}
		});
		};
	};

	var f_download=function(n)
	{
		return async function(){		
			return new Promise((resolve)=>{ 
				console.log("f_download");
				const a = document.createElement('a');
				a.href="file/"+localStorage.getItem("usr_name")+"/"+encodeURIComponent(files[n].name);
				a.download=files[n].name;
				a.click();
				document.body.appendChild(a);
				document.body.removeChild(a);
			});
		};
	};
	xhr.send(JSON.stringify(get_files));//发送请求数据并将其转换为JSON格式
	window.showfile=function()
	{
		return executeAsync(async function(){
			console.log("showfile");
			var main=document.getElementById("main");
			main.innerHTML = "";
			var file_table=document.createElement("ul");
			file_table.className="file_table";
			file_table.id="file_table"
			for(var i=0;i<files.length;i++)
			{
				if(files[i].n!=-1){
					var file_list=document.createElement("li");
						file_list.className="file_list";
						file_list.id="file_list";
					var file_name=document.createElement("div");
						file_name.className="file_name";
						file_name.id="file_name";
						file_name.appendChild(document.createTextNode(files[i].name));
					var file_delete=document.createElement("button");
						file_delete.className="file_delete";
						file_delete.id="file_delete";
						file_delete.onclick=f_delete(i,file_table,file_list);
						file_delete.appendChild(document.createTextNode("删除"));
					var file_size=document.createElement("span");
						file_size.className="file_size";
						file_size.id="file_size";
						file_size.appendChild(document.createTextNode(files[i].size));
					var download=document.createElement("button");
						download.className="download";
						download.id="download";
						download.onclick=f_download(i);
						download.appendChild(document.createTextNode("下载"));
					file_list.appendChild(file_name);
					file_list.appendChild(file_size);
					file_list.appendChild(download);
					file_list.appendChild(file_delete);
					file_table.appendChild(file_list);
				}
			}
			main.appendChild(file_table);
		});
	};

var up_cancel=function(i,file_table,file_list){
	return function(){
		up_queue[i].is_pause=true;
		up_queue[i].n=-1;
		if(file_delete(up_queue[i].name)=="success"){
			file_table.removeChild(file_list);
		}
	}
}

var up_quase=function (n,quase){
	return function(){
		up_queue[n].is_pause=!up_queue[n].is_pause;
		if(quase.innerHTML=="暂停"){
			quase.innerHTML="继续"
		}else{
			quase.innerHTML="暂停"
		}
	}
}
window.show_upqueue=function()
{
		console.log("updown");
		var main=document.getElementById("main");
		main.innerHTML = "";
		var file_table=document.createElement("ul");
		file_table.className="file_table";
		file_table.id="file_table"
		for(var i=0;i<up_queue.length;i++){
				if(up_queue[i].n!=-1){
				var file_list=document.createElement("li");
					file_list.className="file_list" ;
					file_list.id="up_list";
				var file_name=document.createElement("div");
					file_name.className="file_name";
					file_name.id="up_name";
					file_name.appendChild(document.createTextNode(String(up_queue[i].name)));
				var up_pg=document.createElement("span");
					up_pg.className="file_size";
					up_pg.id="up_pg";
				var quase=document.createElement("button");
					quase.className="download";
					quase.id="quase";
					quase.onclick=up_quase(i,quase);
					quase.innerHTML="暂停"
				var cancel=document.createElement("button");
					cancel.className="file_delete";
					cancel.id="cancal";
					cancel.onclick=up_cancel(i,file_table,file_list);
					cancel.innerHTML="取消"

					file_list.appendChild(file_name);
					file_list.appendChild(up_pg);
					file_list.appendChild(quase);
					file_list.appendChild(cancel);
					file_table.appendChild(file_list);
					up_queue_line(i,file_table,up_pg,file_list);
				}
			}
			main.appendChild(file_table);
};

function  up_queue_line(i,file_table,up_pg,file_list) {//每一行的下载信息
		console.log("up_queue_line");
		let timer = setInterval(function(){
			if(up_queue[i].p<100&&up_queue[i].n!=-1){
				up_pg.textContent=String(up_queue[i].p.toFixed(1))+'%';
			}else{
				clearInterval(timer);
				console.log("clear");
				file_table.removeChild(file_list);
				up_queue[i].n=-1;
			}
		},500);//每500ms刷新一次
}

	window.note=function()
	{	
		return executeAsync(async function(){
			console.log("note");
			var main=document.getElementById("main");
			main.innerHTML = "";
		});
	};


	async function  sendchunk(formData,i) {
		return new Promise((resolve, reject) => {
			var xhr = new XMLHttpRequest();
			xhr.addEventListener('load', () => {
				if(xhr.status>=200&&xhr.status<300)
				{
					resolve(xhr.responseText);
				}else{
					reject(new Error('网络错误，上传失败'));
				}
			});
			xhr.addEventListener('error', () => {
				reject(new Error('网络错误，上传失败'));
			});
			xhr.open('POST', '');
			if(up_queue[i].n!=-1&&up_queue[i].is_pause!=true){
				xhr.send(formData);
			}else{
				reject(new Error('上传已完成或已取消或已经暂停'));
			}
		});
	}

	async function ready_send(up_file,i,start,end,chunksize)
		{
				if(up_queue[i].is_pause==false){
					//console.log("ready_send");
					if(up_queue[i].n==-1){
						return;
					}
					if(start>=up_file.size){
						up_queue[i].n==-1;
						up_queue[i].p=100;
						files.push(new file(String(up_file.name),Math_size(up_file.size),files.length));
						console.log("upload success");
						return;
					}
					up_queue[i].p=start/up_file.size*100;
					var chunk=up_file.slice(start,end);
					var formData = new FormData();
					formData.append('path',localStorage.getItem('usr_name')+'/'+up_file.name);
					formData.append('size',end-start);
					formData.append('start',start);
					formData.append("total",up_file.size);
					formData.append('chunk',chunk);
					var re= await sendchunk(formData,i);
					if(Object.prototype.toString.call(re)!='Error'){
						start=parseInt(re)<start?start:parseInt(re);
						console.log(start);
						end = Math.min(start + chunksize, up_file.size);
					}else{
						console.log(re);
					}
				}
			setTimeout(ready_send,0,up_file,i,start,end,chunksize);
		}
	window.upload=function()
	{
		return executeAsync(async function(){
			console.log("upload");
			var input=document.createElement("input");
			input.id="fileInput";
			input.type="file";
			input.multiple="multiple";
			const clickEvent = new MouseEvent('click', {
			bubbles: true,
			cancelable: true
			});
			input.addEventListener('change',async function(e) {
				// 在这里处理选择的文件
				var up_file=e.target.files[0];
				console.log(up_file.name);
				var chunksize=1*1024*1024;//每个块最高1mb
				var start=0, end=Math.min(start + chunksize, up_file.size);
				var i=up_queue.push(new up_line(String(up_file.name),0,up_queue.length))-1;
				console.log(up_file.size);
				ready_send(up_file,i,start,end,chunksize);
			})
			input.dispatchEvent(clickEvent);
		});
	};



 window.addEventListener('beforeunload', function (e) {//当网页关闭重新刷新或关闭时触发
	for(var i=0;i<up_queue.length;i++){
		if(up_queue[i].n!=-1){
			 // 取消事件并显示提示
			e.preventDefault();
			e.returnValue = ''; // 某些浏览器需要设置returnValue
			return '';
		}
	}
 });